<?php

namespace Mouta\UserBundle\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\Exception\FormException;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;


class SocialConnectType extends AbstractType
{
    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        if (array_key_exists('attr', $options))
        {
            $url = "#";
            if($options['attr']['type'] == 1)
            {
                $facebookClient = new \Facebook([
                    'appId' => $this->container->parameters['fos_facebook.app_id'],
                    'secret' => $this->container->parameters['fos_facebook.secret']
                ]);
                $url = $facebookClient->getLoginUrl(array('scope' => ['basic_info', 'read_stream'], 'redirect_uri' => $this->container->get('router')->generate('facebook_connect', array(), true)));

            }
            elseif($options['attr']['type'] == 2)
            {
                $storage = new \OAuth\Common\Storage\Session();
                $credentials = new \OAuth\Common\Consumer\Credentials(
                    $this->container->parameters['twitter_api_key'],
                    $this->container->parameters['twitter_api_secret'],
                    $this->container->get('router')->generate('twitter_connect', array(), true)
                );
                $serviceFactory = new \OAuth\ServiceFactory();
                $serviceFactory->setHttpClient(new \OAuth\Common\Http\Client\CurlClient());
                $twitterService = $serviceFactory->createService('twitter', $credentials, $storage);
                $token = $twitterService->requestRequestToken();
                $url = $twitterService->getAuthorizationUri(['oauth_token' => $token->getRequestToken()]);
            }

            $view->vars['url'] = htmlspecialchars_decode($url);
        }

    }

    public function getParent()
    {
        return 'text';
    }
    
    public function getName()
    {
        return 'social_connect';
    }
}
